package com.xinshujia.filter.authentication;

import com.alibaba.nacos.common.http.param.MediaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xinshujia.dto.LoginDTO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.BufferedReader;
import java.io.IOException;

/**
 * @author: 野狼上校
 * @create: 2023-05-30  22:33
 * @version: 1.0
 * @description: 自定义账号登录过滤器
 */
public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        //1. 判断请求方式
        if (!request.getMethod().equalsIgnoreCase("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
            //2. 判断请求的数据类型
        } else if (!MediaType.APPLICATION_JSON.toLowerCase().contains(request.getContentType().toLowerCase())) {
            throw new AuthenticationServiceException("Authentication contentType not supported: " + request.getContentType());
        } else {
            // 3. 从请求体中读取JSON数据 (用户名和密码)
            StringBuilder buffer = new StringBuilder();
            LoginDTO loginDTO;
            try {
                BufferedReader reader = request.getReader();
                String line;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
                // 解析JSON
                ObjectMapper objectMapper = new ObjectMapper();
                loginDTO = objectMapper.readValue(buffer.toString(), LoginDTO.class);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            String username = loginDTO.getUsername();
            username = username != null ? username.trim() : "";
            String password = loginDTO.getPassword();
            password = password != null ? password : "";

            //4. 认证
            UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username, password);
            this.setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }
    }
}
